<template>
  <input type="file" @change="handleFileChange"/>
  <button @click="exportToExcel">导出到Excel</button>
</template>

<script setup lang="ts">
import {ref} from 'vue';
// import XLSX from 'xlsx';
import * as XLSX from 'xlsx';

const fileContent = ref('');
const dataForExcel = ref([]);

const handleFileChange = (event) => {
  dataForExcel.value=[]
  const file = event.target.files[0];
  if (!file) return;
  const reader = new FileReader();
  reader.onload = (e) => {
    fileContent.value = e.target.result;
    parseFileContent();
  };
  reader.readAsText(file);
};

const parseFileContent = () => {
  const lines = fileContent.value.split('\n');
  let title = '';
  let currentData = {};

  lines.forEach((line) => {
    line = line.trim();
    if (!line) return;
    console.log(`forEach line:${line}`)

    // 如果当前section有数据且新的section开始，则保存当前数据并清空
    if (title && line.startsWith('【')) {
      dataForExcel.value.push(currentData);
      currentData = {};
      title = line.slice(1, -1);
    }

    if (line.startsWith('【') && line.endsWith('】')) {
      title = line.slice(1, -1);
      console.log(`currentSection:${title}`)
      currentData = {title: title};
    } else if (line.startsWith('用户名：')) {
      currentData.username = line.replace('用户名：', '');
    } else if (line.startsWith('密码：')) {
      currentData.password = line.replace('密码：', '');
    } else if (line.startsWith('链接：')) {
      currentData.link = line.replace('链接：', '');
    } else if (line.startsWith('说明：')) {
      currentData.description = line.replace('说明：', '');
    } else {
      currentData.description += ('\n\r' + line);
    }
    console.log(`currentData:${JSON.stringify(currentData)}`)

  });
  // 处理最后一个section的数据
  if (Object.keys(currentData).length) {
    dataForExcel.value.push(currentData);
  }
};

const exportToExcel = () => {
  const ws = XLSX.utils.json_to_sheet(dataForExcel.value, {header: ['title', 'username', 'password', 'link', 'description']});
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, 'credentials.xlsx');
};
</script>